#!/bin/bash
set -e

SCRIPT_DIR=$(realpath $(dirname "$0"))
CURRENT_DIR=$(realpath $(pwd))

OPER="create"
REPO_FILE=""
NAME=""
BASEURL=""
PRIOR=""

source $SCRIPT_DIR/common.sh

function repofile_create()
{
    local filename=$(realpath $1)
    local name=$2
    local url=$3
    local pri=$4

    echo "[$name]" > $filename
    echo "name=$name" >> $filename
    echo "baseurl=$url" >> $filename
    echo "enabled=1" >> $filename
    echo "gpgcheck=0" >> $filename
    echo "priority=$pri" >> $filename
}

function repofile_addtop()
{
    local filename=$(realpath $1)
    local name=$2
    local url=$3
    local pri=$4

    local tmpf=$filename.bak

    echo "[$name]" > $tmpf
    echo "name=$name" >> $tmpf
    echo "baseurl=$url" >> $tmpf
    echo "enabled=1" >> $tmpf
    echo "gpgcheck=0" >> $tmpf
    echo "priority=$pri" >> $tmpf
    cat $filename >> $tmpf
    rm -f $filename
    mv $tmpf $filename
}

function usage()
{
    log_info "Usage: ./$(basename $0) addtop|create -r [repo] -s [baseurl] -n [repo name] -p [priority]"
}

function param_parse()
{
    OPER=$1
    ( [[ x$OPER != x"addtop" ]] && [[ x$OPER != x"create" ]] ) && usage && return 1
    shift

    while getopts "r:s:n:p:" opt
    do
        case "$opt" in
            r)
            REPO_FILE="$OPTARG";;
            s)
            BASEURL="$OPTARG";;
            n)
            NAME="$OPTARG";;
            p)
            PRIOR="$OPTARG";;
            ?)
            log_error "unknown parameters" && usage && return 1;;
        esac
    done

    [[ ! -n $REPO_FILE ]] && log_error "empty parameter, -r" && usage && return 1
    [[ ! -n $BASEURL ]] && log_error "empty parameter, -s" && usage && return 1
    [[ ! -n $NAME ]] && log_error "empty parameter, -n" && usage && return 1
    [[ ! -n $PRIOR ]] && log_error "empty parameter, -p" && usage && return 1

    [[ ! -d $(dirname $REPO_FILE) ]] && log_error "user specific file's path not exist" && return 1
    REPO_FILE=$(realpath $REPO_FILE)

    [[ -d $BASEURL ]] && BASEURL=$(realpath $BASEURL)
    [[ $PRIOR -lt 1 ]] && [[ $PRIOR -gt 100 ]] && log_error "invalid priorty" && usage && return 1

    return 0
}

function main()
{
    param_parse $@

    [[ $OPER = "addtop" ]] && repofile_addtop $REPO_FILE $NAME $BASEURL $PRIOR
    [[ $OPER = "create" ]] && repofile_create $REPO_FILE $NAME $BASEURL $PRIOR

    return 0
}

main $@
